import time
import cv2
import numpy as np
from PySide6.QtWidgets import (
    QApplication, QWidget, QVBoxLayout,
    QPushButton, QLabel, QRadioButton, QButtonGroup
)
from PySide6.QtCore import QTimer
from PySide6.QtGui import QImage, QPixmap

from config.config_manager import load_config, save_user_config
from core.app_core import AppCore
from core.capture.capture_mss import MSSCapture


class MainWindow(QWidget):
    def __init__(self):
        super().__init__()
        self.setWindowTitle("AI 瞄准 Demo")
        self.cfg = load_config()
        self.core = AppCore(self.cfg)

        layout = QVBoxLayout()
        self.label = QLabel("状态: 未运行")
        layout.addWidget(self.label)

        # -------- 启动 / 停止 --------
        btn_start = QPushButton("启动核心流程")
        btn_start.clicked.connect(self.on_start)
        layout.addWidget(btn_start)

        btn_stop = QPushButton("停止核心流程")
        btn_stop.clicked.connect(self.on_stop)
        layout.addWidget(btn_stop)

        # -------- 截图方式选择 --------
        layout.addWidget(QLabel("截图方式:"))
        self.capture_group = QButtonGroup(self)

        rb_mss = QRadioButton("MSS")
        rb_win32 = QRadioButton("Win32")
        rb_dxgi = QRadioButton("DXGI")

        self.capture_group.addButton(rb_mss)
        self.capture_group.addButton(rb_win32)
        self.capture_group.addButton(rb_dxgi)

        layout.addWidget(rb_mss)
        layout.addWidget(rb_win32)
        layout.addWidget(rb_dxgi)

        # 设置当前选中值
        current_mode = self.cfg["screen"]["capture"].lower()
        if current_mode == "mss":
            rb_mss.setChecked(True)
        elif current_mode == "win32":
            rb_win32.setChecked(True)
        elif current_mode == "dxgi":
            rb_dxgi.setChecked(True)

        # 信号连接
        rb_mss.toggled.connect(lambda checked: self.on_capture_changed("mss", checked))
        rb_win32.toggled.connect(lambda checked: self.on_capture_changed("win32", checked))
        rb_dxgi.toggled.connect(lambda checked: self.on_capture_changed("dxgi", checked))

        # -------- 手动更新按钮 --------
        btn_update = QPushButton("更新配置 (从磁盘读取)")
        btn_update.clicked.connect(self.on_update)
        layout.addWidget(btn_update)

        # -------- 截图显示 --------
        self.capture_label = QLabel("截图预览区")
        self.capture_label.setFixedSize(320, 320)
        layout.addWidget(self.capture_label)

        # -------- FPS 显示 --------
        self.fps_label = QLabel("FPS: 0.0")
        layout.addWidget(self.fps_label)

        self.setLayout(layout)

        # 初始化截图器（默认 mss）
        self.mss_cap = MSSCapture(
            monitor=self.cfg["screen"].get("monitor", 1),
            width=self.cfg["screen"].get("width", 320),
            height=self.cfg["screen"].get("height", 320),
        )
        self.mss_cap.init_in_thread()

        # FPS 统计用变量
        self.last_time = time.time()
        self.frame_count = 0

        # 定时刷新截图
        self.timer = QTimer(self)
        self.timer.timeout.connect(self.update_frame)
        self.timer.start(30)  # 每 30ms ~ 33FPS

    # ------------------- 功能区 -------------------
    def on_start(self):
        self.core.start()
        self.label.setText("状态: 运行中")

    def on_stop(self):
        self.core.stop()
        self.label.setText("状态: 已停止")

    def on_capture_changed(self, mode: str, checked: bool):
        """单选切换时：修改配置 → 写文件 → 更新核心"""
        if checked:
            self.cfg["screen"]["capture"] = mode
            save_user_config(self.cfg)
            self.core.update_config(self.cfg)
            self.label.setText(f"状态: 已切换到 {mode.upper()}")
            print(f"🔄 截图模式已切换为 {mode}")

    def on_update(self):
        """手动从磁盘读取配置"""
        new_cfg = load_config()
        self.cfg = new_cfg
        self.core.update_config(new_cfg)
        self.label.setText("状态: 配置已从磁盘更新")
        print("🔄 从 user.yaml 重新加载配置")

    def update_frame(self):
        frame = self.core.last_frame
        if frame is None:
            return
        rgb = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
        h, w, ch = rgb.shape
        qimg = QImage(rgb.data, w, h, ch * w, QImage.Format_RGB888)
        self.capture_label.setPixmap(QPixmap.fromImage(qimg))

        # --- FPS 统计 ---
        self.frame_count += 1
        now = time.time()
        if now - self.last_time >= 1.0:
            fps = self.frame_count / (now - self.last_time)
            self.fps_label.setText(f"FPS: {fps:.1f}")
            self.frame_count = 0
            self.last_time = now


def run_ui():
    app = QApplication([])
    win = MainWindow()
    win.show()
    app.exec()
